# -*- coding: utf-8 -*-
"""
@Time ： 2020/8/11 21:04
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：京东验证码
"""
import random
import time
import pyautogui
from selenium import webdriver
from selenium.webdriver import ActionChains
from common.ver.slide import Slide


def slide_by_pyautogui(x, y, offset):
    """
    使用pyautogui滑动
    :param x: 开始位置x
    :param y: 开始位置y
    :param offset: 互动横坐标偏移量
    :return:
    """
    xx = x + offset
    pyautogui.moveTo(x, y, duration=0.1)
    pyautogui.mouseDown()  # 按下鼠标键
    y += random.randint(9, 19)
    pyautogui.moveTo(x + int(offset * random.randint(15, 23) / 20), y, duration=0.28)
    y += random.randint(-9, 0)
    pyautogui.moveTo(x + int(offset * random.randint(17, 21) / 20), y,
                     duration=(random.randint(20, 31)) / 100)  # 鼠标拖动到坐标(1566,706)位置处
    y += random.randint(0, 8)
    # pyautogui.moveTo(x + int(offset * 0.1), y, duration=0.15)
    # y += random.randint(-10, 10)
    pyautogui.moveTo(xx, y, duration=0.3)
    pyautogui.mouseUp()  # 松开鼠标


driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://passport.jd.com/new/login.aspx')

driver.find_element_by_xpath('//*[@id="content"]/div[2]/div[1]/div/div[3]/a').click()
driver.find_element_by_xpath('//*[@id="loginname"]').send_keys('dsklfjaoi')
driver.find_element_by_xpath('//*[@id="nloginpwd"]').send_keys('dfsfads')
driver.find_element_by_xpath('//*[@id="loginsubmit"]').click()

while True:

    ele1 = driver.find_element_by_xpath('//*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[1]/div[2]/div[1]/img')
    ele2 = driver.find_element_by_xpath('//*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[1]/div[2]/div[2]/img')
    slide = Slide(driver)
    base64_bg = ele1.get_attribute('src')
    base64_bg = base64_bg[22:]
    base64_block = ele2.get_attribute('src')
    base64_block = base64_block[22:]

    import base64

    f = open('../lib/verify/bg.jpg', mode='wb')
    # 写入图片的二进制码
    f.write(base64.b64decode(base64_bg))
    f.close()
    f = open('../lib/verify/block.jpg', mode='wb')
    # 写入图片的二进制码
    f.write(base64.b64decode(base64_block))
    f.close()

    # 计算缩放，看你的分辨率是否放大了
    x = slide.FindPic('../lib/verify/bg.jpg', '../lib/verify/block.jpg')
    x = int(x * ele1.size.get('width') * 1.25 / 360)
    print(x)
    print(ele2.location)
    start_x = int(ele2.location.get('x') * 1.25) + 20
    start_y = int(ele2.location.get('y') * 1.25) + 165

    slide_by_pyautogui(start_x, start_y, x)
    print(start_x, start_y)

    time.sleep(2)
    try:
        driver.find_element_by_xpath('//*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[1]/div[2]/div[2]/img').click()
    except:
        break
